package Database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import org.apache.log4j.Logger;

public class ConnectionProvider {

    /*
     * Clase ConnectionProvider
     *
     * Provee la funcionalidad basica para manejar una conexion con una base de
     * datos Derby.
     */
    
    private static ConnectionProvider instance;
    private static final Logger LOGGER = Logger.getLogger(ConnectionProvider.class);
    private Connection connection = null;

    public ConnectionProvider() {
        try {
            Class.forName("org.apache.derby.jdbc.ClientDriver");
        } catch (ClassNotFoundException e) {
            LOGGER.error("Error al cargar los Drivers de Coneccion a Derby", e);
        }
    }

    public static ConnectionProvider getInstance() {
        if (instance == null) {
            instance = new ConnectionProvider();
        }
        return instance;
    }

    public Connection getConnection(String derbyURL, String userName, String password) throws SQLException {
        if (connection == null || (connection != null && connection.isClosed())) {
            connection = DriverManager.getConnection(derbyURL, userName, password);
            LOGGER.debug("Nueva Coneccion");
        }
        return connection;
    }

    public void closeConnection() {
        try {
            if (connection != null && !connection.isClosed()) {
                connection.close();
                connection = null;
            }
        } catch (SQLException e) {
        }
    }
}
